package com.saber;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息消费者
 * Created by PC on 2017/10/18.
 */
public class Consumer {


    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置RabbitMQ地址
        factory.setHost(Product.host);
        factory.setPort(Product.port);
        factory.setUsername(Product.userName);
        factory.setPassword(Product.password);
        //创建一个新的连接
        Connection connection = factory.newConnection();
        //创建一个通道
        Channel channel = connection.createChannel();
        //声明要关注的队列
        channel.queueDeclare(Product.QUEUE_NAME,false,false,false,null);
        System.out.println("Customer Waiting Received messages");
        //DefaultConsumer类实现了Consumer接口，通过传入一个通道，
        //告诉服务器我们需要哪个频道的消息，如果频道中有消息，就会执行回调函数 handleDelivery
        com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                String message = new String(body,"UTF-8");
                System.out.println("Customer Received message = " + message);
                super.handleDelivery(consumerTag, envelope, properties, body);
            }
        };
        //自动回复队列应答 --RbbitMQ中的消息确认机制
        channel.basicConsume(Product.QUEUE_NAME,true,consumer);

        channel.close();
        connection.close();
    }
}
